# Flask扩展初始化文件
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_cors import CORS
from flask_redis import FlaskRedis
from flask_login import LoginManager
from config.redis_config import RedisConfig

# 初始化扩展对象
db = SQLAlchemy()
migrate = Migrate()
cors = CORS()
redis_client = FlaskRedis()
login_manager = LoginManager()

def init_extensions(app):
    """
    初始化所有扩展
    :param app: Flask应用实例
    """
    db.init_app(app)
    migrate.init_app(app, db)
    
    # 使用配置中的CORS_ORIGINS初始化CORS
    cors.init_app(app, origins=app.config.get('CORS_ORIGINS', ["*"]))
    
    # 初始化Redis
    app.config['REDIS_URL'] = RedisConfig.get_redis_url()
    app.config['REDIS_HOST'] = RedisConfig.REDIS_HOST
    app.config['REDIS_PORT'] = RedisConfig.REDIS_PORT
    app.config['REDIS_PASSWORD'] = RedisConfig.REDIS_PASSWORD
    app.config['REDIS_DB'] = RedisConfig.REDIS_DB
    app.config['REDIS_CONNECTION_POOL_KWARGS'] = {
        'max_connections': RedisConfig.REDIS_CONNECTION_POOL_MAX_CONNECTIONS,
        'retry_on_timeout': RedisConfig.REDIS_CONNECTION_POOL_RETRY_ON_TIMEOUT,
        'socket_timeout': RedisConfig.REDIS_SOCKET_TIMEOUT,
        'socket_connect_timeout': RedisConfig.REDIS_SOCKET_CONNECT_TIMEOUT,
    }
    
    redis_client.init_app(app)
    
    # 初始化Flask-Login
    login_manager.init_app(app)
    login_manager.login_view = 'auth.login'
    login_manager.login_message = '请先登录以访问此页面。'
    login_manager.login_message_category = 'info'